//
//  MarketDetailTableViewController.m
//  bondwatch_purecode
//
//  Created by Jason Yuan on 5/26/15.
//  Copyright (c) 2015 Sumridge. All rights reserved.
//

#import "MarketDetailTableViewController.h"
#import "MarketDetailTableViewCell.h"
#import "MarketDetailViewController.h"
#import "SearchViewController.h"
#import "WantedBondTableViewController.h"
#import "TargetLevel.h"
#import "TargetLevelView.h"

#define TitleFont [UIFont fontWithName:@"Arial-BoldMT" size:11.0];
#define TargetFont [UIFont fontWithName:@"Arial-BoldMT" size:12.0];

@interface MarketDetailTableViewController () <UITableViewDataSource, UITableViewDelegate, TargetLevelViewDelegate>
{
    NSDictionary *myListInfo;
    NSMutableArray *dataArray;
    NSMutableDictionary *offerData;
    
    UITableView *myTableView;
    
    TargetLevelView *targetLevelView;
}

@end

@implementation MarketDetailTableViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    [self getData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.title = [Shared shared].prwName;
    
    myTableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    myTableView.separatorInset = UIEdgeInsetsZero;
    myTableView.delegate = self;
    myTableView.dataSource = self;
    [self.view addSubview:myTableView];
    
    UIBarButtonItem *settingBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Settings"] style:UIBarButtonItemStylePlain target:self action:@selector(settingBarButtonPressed:)];
    settingBarButton.tintColor = SUMRIDGECOLOR;
    
    UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Back"] style:UIBarButtonItemStylePlain target:self action:@selector(backBarButtonPressed:)];
    backBarButton.tintColor = SUMRIDGECOLOR;
    
    NSArray *leftBarButtonArray = @[settingBarButton, backBarButton];
    self.navigationItem.leftBarButtonItems = leftBarButtonArray;
    
    UIBarButtonItem *refreshBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Refresh"] style:UIBarButtonItemStylePlain target:self action:@selector(refreshBarButtonPressed:)];
    refreshBarButton.tintColor = SUMRIDGECOLOR;
    
    UIBarButtonItem *searchBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Search"] style:UIBarButtonItemStylePlain target:self action:@selector(searchBarButtonPressed:)];
    searchBarButton.tintColor = SUMRIDGECOLOR;
    
    NSArray *rightBarButtonArray = @[refreshBarButton, searchBarButton];
    self.navigationItem.rightBarButtonItems = rightBarButtonArray;
    
    UISwipeGestureRecognizer *swipeGestureRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(backBarButtonPressed:)];
    swipeGestureRight.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swipeGestureRight];
    
    targetLevelView = [[TargetLevelView alloc] initWithFrame:self.view.bounds];
    targetLevelView.delegate = self;
    [targetLevelView setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:0.5]];
    targetLevelView.hidden = YES;
    [self.view addSubview:targetLevelView];
}

- (void)settingBarButtonPressed:(id)sender {
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

- (void)backBarButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)refreshBarButtonPressed:(id)sender {
    [self getData];
}

- (void)getData {
    dataArray = nil;
    [myTableView reloadData];
    
    NSDictionary *params = @{@"prwId" : [Shared shared].prwId};
    [MBProgressHUD showHUDAddedTo:self.view animated:YES].dimBackground = YES;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    [manager GET:LISTDETAILURL parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSArray *data = [responseObject objectForKey:@"data"];
        dataArray = [[NSMutableArray alloc] init];
        if (![data isEqual:[NSNull null]]) {
            for (NSDictionary *dictionary in data) {
                NSMutableDictionary *mDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary];
                [dataArray addObject:mDictionary];
            }
            targetLevelView.dataArray =  dataArray;
            DDLogVerbose(@"List Detail Data is:\n%@", dataArray);
            [self getOfferData:dataArray];
        } else {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        if (response.statusCode == 200) {
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            return;
        }
        
        DDLogError(@"Get list detail data error:\n%@", error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"Network Error.";
        hud.detailsLabelText = @"Please retry later.";
        
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            // Do something...
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
    }];
}

- (void)searchBarButtonPressed:(id)sender {
    SearchViewController *searchViewController = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searchViewController animated:YES];
}

- (void)getOfferData:(NSMutableArray *)array {
    NSMutableArray *params = [[NSMutableArray alloc] init];
    for (NSDictionary *dictionary in array) {
        NSString *cusip = [dictionary objectForKey:@"cusip"];
        [params addObject:cusip];
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    [manager POST:OFFERPRICE parameters:params success:^(NSURLSessionDataTask *task, id JSON) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        offerData = [NSMutableDictionary dictionaryWithDictionary:[JSON objectForKey:@"data"]];
        DDLogVerbose(@"OfferData is:\n%@", offerData);
        [myTableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        DDLogError(@" Get offer data error:\n%@", error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"Network Error.";
        hud.detailsLabelText = @"Please retry later.";
        
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            // Do something...
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (![dataArray isEqual:[NSNull null]]) {
        return [dataArray count];
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MarketDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MarketDetail"];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[MarketDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MarketDetail"];
        cell.separatorInset = UIEdgeInsetsZero;
    }
    NSDictionary *dictionary = [dataArray objectAtIndex:indexPath.row];
    NSString *cusip = [dictionary objectForKey:@"cusip"];
    [cell setUIFrame];
    if (indexPath.row < [dataArray count]) {
        [cell setLabelText:dictionary offerData:[offerData objectForKey:cusip]];
    }
    
    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([UIScreen mainScreen].bounds.size.width > 414.0) {
        return 30.0;
    } else {
        return 55.0;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < [dataArray count]) {
        NSDictionary *data = [dataArray objectAtIndex:[indexPath row]];
        [Shared shared].bondInfo = @{@"cusip" : [data objectForKey:@"cusip"], @"marketSectorDes" : [data objectForKey:@"marketSectorDes"], @"description": [data objectForKey:@"description"]};
        
        MarketDetailViewController *marketDetailViewController = [[MarketDetailViewController alloc] init];
        [self.navigationController pushViewController:marketDetailViewController animated:YES];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewRowAction *targetLevelAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"Target Level" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        targetLevelView.hidden = NO;
        targetLevelView.currentIndexPath = indexPath;
        [targetLevelView.targetField becomeFirstResponder];
        
        NSDictionary *dictionary = [dataArray objectAtIndex:indexPath.row];
        
        [TargetLevel sharedInstance].cusip = [dictionary objectForKey:@"cusip"];
        NSString *issuer = [dictionary objectForKey:@"issuer"];
        NSString *description = [dictionary objectForKey:@"description"];
        
        targetLevelView.titleLabel1.text = [NSString stringWithFormat:@"%@-%@", issuer, [TargetLevel sharedInstance].cusip];
        targetLevelView.titleLabel2.text = description;
    }];
    targetLevelAction.backgroundColor = [UIColor grayColor];
    
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"Delete" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        // Delete the row from the data source
        NSDictionary *dictionary = [dataArray objectAtIndex:indexPath.row];
        NSString *cusip = [dictionary objectForKey:@"cusip"];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES].dimBackground = YES;
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?prwId=%@", DELETEDATAURL, [Shared shared].prwId]]];
        [request setHTTPMethod:@"POST"];
        
        [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        
        NSMutableData *postBody = [NSMutableData data];
        [postBody appendData:[cusip dataUsingEncoding:NSUTF8StringEncoding]];
        [request setHTTPBody:postBody];
        
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
        operation.responseSerializer = [AFHTTPResponseSerializer serializer];
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            DDLogVerbose(@"Delete %@ result:\n%@", cusip, result);
            NSDictionary *dictionary = [result objectFromJSONString];
            bool success = [dictionary objectForKey:@"success"];
            if (success) {
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.labelText = [NSString stringWithFormat:@"Delete Bond(%@) successfully.", cusip] ;
                
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                    // Do something...
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                });
                [dataArray removeObjectAtIndex:indexPath.row];
                [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            } else {
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.labelText = [NSString stringWithFormat:@"Delete Bond(%@) failure.", cusip];
                hud.detailsLabelText = @"Please try again.";
                
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                    // Do something...
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                });
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            DDLogError(@"Delete %@ error:\n%@", cusip, error);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
        [[NSOperationQueue mainQueue] addOperation:operation];
    }];
    
    return @[deleteAction, targetLevelAction];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Setting Rotate

- (BOOL)shouldAutorotate {
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [myTableView reloadData];
}



- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
//    [self.tableView reloadData];
}

#pragma mark - TargetLevel view delegate

- (void)reloadTableView:(NSIndexPath *)indexPath {
     [myTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

- (void)sessionTimeOut {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

@end
